//
//  NetworkTools.swift
//  swift_learning
//
//  Created by aron on 2017/1/31.
//  Copyright © 2017年 arons. All rights reserved.
//

import UIKit
import AFNetworking

enum RequestType : String {
    case GET = "GET"
    case POST = "POST"
}

class NetworkTools {
    
    static let sessionManager : AFHTTPSessionManager = {
        let sessionManager = AFHTTPSessionManager.init()
        sessionManager.responseSerializer.acceptableContentTypes?.insert("text/html")
        sessionManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return sessionManager
    }()
    
    static let sharedInstance : NetworkTools  = {
        let tools = NetworkTools()
        return tools;
    }()
    
    // @noescape属性是在 Swift1.2中引入的，把传入闭包参数的调用限制在调用的函数体内，对性能有一定的提升，同时将闭包标注为@noescape使你能在闭包中隐式地引用self。默认是noescape
    func request(method: RequestType, urlString: String, params: [String: Any], resultBlock: @escaping (_ result : Any?, _ error : Error?) -> ()) {
        
        // DEBUG打印
        BMLOG("\n>>>>>request:\(urlString)$$\(params)")
        
        let successBlock = { (task : URLSessionDataTask, result : Any?) in
            resultBlock(result, nil)
            
            // DEBUG打印
            BMLOG("\n>>>>>response:\(urlString)$$\(result ?? nil)")
        }
        
        let failureBlock = { (task : URLSessionDataTask?, error : Error) in
                resultBlock(nil, error)
            
            // DEBUG打印
            BMLOG("\n>>>>>response:\(urlString)$$\(error)")
        }
        
        if method == .GET {
            NetworkTools.sessionManager.get(urlString, parameters: params, progress: nil, success: successBlock, failure: failureBlock)
        }else if method == .POST {
            NetworkTools.sessionManager.post(urlString, parameters: params, progress: nil, success: successBlock, failure: failureBlock)
        }
    }
}

// MARK: - ......::::::: 业务接口 :::::::......
extension NetworkTools {
    
    /// 获取AccessToken
    func requestAccessToken(code : String, finished : @escaping (_ result: UserAccount?, _ error: Error?)->()) {
        // 使用Code换取accesstoken
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params : [String : Any] = ["client_id" : Constants.AppKey,
                                       "client_secret" : Constants.AppSecret,
                                       "grant_type" : "authorization_code",
                                       "code" : code,
                                       "redirect_uri" : Constants.CallBack]

        request(method: .POST, urlString: urlString, params: params) { (result : Any?, error: Error?) in
            
            if error != nil {
                finished(nil, error);
                return;
            }
            
            guard let accountInfoDict : [String: Any] = result as! [String : Any]? else {
                finished(nil, error);
                return;
            }
            
            let userAcc = UserAccount(dict: accountInfoDict);
            finished(userAcc, error);
        }
    }
    
    
    /// 获取用户信息
    func requestUserInfo(acc: UserAccount, finished : @escaping (_ result: UserAccount?, _ error: Error?)->()) {
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        let params : [String : Any] = ["access_token" : acc.access_token ?? "",
                                       "uid" : acc.uid ?? ""]
        request(method: .GET, urlString: urlString, params: params) { (result : Any?, error: Error?) in
            
            if error != nil {
                finished(nil, error);
                return;
            }
            
            guard let userInfoDict : [String: Any] = result as! [String : Any]? else {
                finished(nil, error);
                return;
            }
            
            acc.screen_name = userInfoDict["screen_name"] as? String
            acc.avatar_large = userInfoDict["avatar_large"] as! String?

            finished(acc, error);
        }
    }
    
    
    func requestStatus(since_id : Int, max_id : Int, finished : @escaping (_ results : [Status]?, _ error : Error?) -> Void) {
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        let params : [String : Any] = ["access_token" : UserAccountManager.sharedInstance.account?.access_token ?? "",
                                       "since_id" : since_id,
                                       "max_id" : max_id]
        
        request(method: .GET, urlString: urlString, params: params) { (result : Any?, error: Error?) in
            
            if error != nil {
                finished(nil, error);
                return;
            }
            
            guard let statusesDict : [String: Any] = result as! [String : Any]? else {
                finished(nil, error);
                return;
            }
            
            
            guard let statusDictArr : [[String : Any]] = statusesDict["statuses"] as! [[String : Any]]? else {
                return;
            }
            
            var statuses : [Status] = [Status]()
            for statusDict : [String : Any] in statusDictArr {
                let status = Status(dict: statusDict)
                statuses.append(status)
            }
            
            finished(statuses, nil)
        }
    }
}
